package com.sloth.bear.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sloth.bear.config.OssProperties;
import com.sloth.bear.service.OssStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 七牛云存储服务实现
 */
@Slf4j
@Service("qiniuStorageService")
@ConditionalOnProperty(name = "oss.type", havingValue = "qiniu")
public class QiniuStorageServiceImpl implements OssStorageService {

    private final UploadManager uploadManager;
    private final Auth auth;
    private final String bucket;
    private final String domain;

    public QiniuStorageServiceImpl(OssProperties ossProperties) {
        OssProperties.QiniuConfig config = ossProperties.getQiniu();

        // 自动识别区域
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;

        this.uploadManager = new UploadManager(cfg);
        this.auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        this.bucket = config.getBucket();
        this.domain = config.getDomain();

        log.info("七牛云存储服务初始化成功，bucket: {}", bucket);
    }

    @Override
    public String upload(MultipartFile file, String filePath) throws Exception {
        // 生成上传凭证
        String upToken = auth.uploadToken(bucket);

        try {
            // 上传文件
            Response response = uploadManager.put(file.getBytes(), filePath, upToken);

            // 解析上传结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("七牛云上传成功: key={}, hash={}", putRet.key, putRet.hash);

            // 返回文件访问URL
            return domain + "/" + filePath;

        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error("七牛云上传失败: {}", r.toString());
            try {
                log.error("错误详情: {}", r.bodyString());
            } catch (QiniuException ex2) {
                // ignore
            }
            throw new RuntimeException("上传文件到七牛云失败: " + ex.getMessage());
        }
    }

    @Override
    public boolean delete(String filePath) {
        try {
            com.qiniu.storage.BucketManager bucketManager = new com.qiniu.storage.BucketManager(auth, new Configuration(Region.autoRegion()));
            bucketManager.delete(bucket, filePath);
            log.info("七牛云删除文件成功: {}", filePath);
            return true;
        } catch (QiniuException e) {
            log.error("七牛云删除文件失败: {}", filePath, e);
            return false;
        }
    }
}
